﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using ASBCC.WebCache;
using ASBCC.Database.Entity;
using ASBCC.Database.Service;
using System.Data;

namespace ASBCC.Workflow.K2Manager
{
    public static class K2DataHelper
    {
        public static Guid InsertActionRecord(
            string activityName, string actionType, string actionName, string auditRule,
            int ownerId, string ownerEn, string ownerCn, 
            int delegateFromId, string delegateFromEn, string delegateFromCn, 
            int procInstID, K2ActionRecordStatus status, string dataFields, string xmlFields)
        {
            Flow_ActionRecordTableEntity entity = new Flow_ActionRecordTableEntity();
            Guid guid = Guid.NewGuid();
            entity.ActionDate = DateTime.Now;
            entity.ActionType = actionType;
            entity.ActionName = actionName;
            entity.AuditRule = auditRule;
            entity.ActionRecordID = guid;
            entity.ActivityName = activityName;
            entity.OwnerID = ownerId;
            entity.OwnerEn = ownerEn;
            entity.OwnerCn = ownerCn;
            entity.DelegateFromID = delegateFromId;
            entity.DelegateFromEn = delegateFromEn;
            entity.DelegateFromCn = delegateFromCn;
            entity.DataFields = dataFields;
            entity.ProcInstID = procInstID;
            entity.Status = (int)status;
            entity.XmlFields = xmlFields;
            Flow_ActionRecordManager.Insert(entity);
            return guid;
        }

        public static void InsertProcessLog(Flow_ProcessLogTableEntity processLog)
        {
            Flow_ProcessLogManager.Insert(processLog);
        }

        public static void InsertProcessStamp(Flow_ProcessStampTableEntity processStamp)
        {
            Flow_ProcessStampManager.Insert(processStamp);
        }

        public static int ClearDisabledProcessStamp(int procInstID)
        {
            return K2DataService.ClearDisabledProcessStamp(procInstID);
        }

        public static int DisableProcessStamp(int procInstID)
        {
            return K2DataService.DisableProcessStamp(procInstID);
        }

        /// <summary>
        /// 清除相关操作图章
        /// </summary>
        /// <param name="procInstID"></param>
        /// <param name="actionRecordID"></param>
        public static int DisableProcessStampByActionRecordId(Guid actionRecordId)
        {
            return K2DataService.DisableProcessStampByActionRecordId(actionRecordId);
        }

        public static int DisableProcessComment(int procInstID)
        {
            return K2DataService.DisableProcessComment(procInstID);
        }

        public static int ClearDisabledProcessComment(int procInstID)
        {
            return K2DataService.ClearDisabledProcessComment(procInstID);
        }

        /// <summary>
        /// 清除相关操作意见
        /// </summary>
        /// <param name="procInstID"></param>
        /// <param name="actionRecordID"></param>
        public static int DisableProcessCommentByActionRecordId(Guid actionRecordId)
        {
            return K2DataService.DisableProcessCommentByActionRecordId(actionRecordId);
        }

        public static void InsertLeadingTime(Flow_LeadingTimeTableEntity leadingTime)
        {
            Flow_LeadingTimeManager.Insert(leadingTime);
        }
        
        public static void InsertProcessComment(Flow_ProcessCommentTableEntity processComment)
        {
            Flow_ProcessCommentManager.Insert(processComment);
        }

        public static Flow_ActionRecordTableEntity GetLastActionRecord(int procInstID)
        {
            return K2DataService.GetLastActionRecord(procInstID);
        }

        public static MyActivityTableEntity GetOneOfMyActivities(int procInstId, int[] statusArr)
        {
            MyActivityTableEntitySet es = GetMyActivities(procInstId, statusArr);
            if (es == null || es.Count == 0) return null;
            return es[0];
        }

        public static MyActivityTableEntitySet GetMyActivities(int procInstId, int[] statusArr)
        {
            string statusText = string.Empty;
            List<string> statusList = new List<string>();
            foreach (int status in statusArr)
            {
                statusList.Add(status.ToString());
            }
            if (statusArr != null || statusArr.Length > 0) statusText = string.Join(",", statusList.ToArray());

            string condition = string.Empty;
            if (!string.IsNullOrEmpty(statusText)) condition = string.Format(" and Status in ({0})", statusText);

            MyActivityTableEntitySet es = MyActivityManager.SelectByCondition(string.Format("K2ProcInstID={0} {1}", procInstId, condition));
            if (es == null) return null;
            return es;
        }

        /// <summary>
        /// 挂起MyActivity
        /// </summary>
        /// <param name="procInstID"></param>
        public static void SuspendMyActivities(int procInstID)
        {
            K2DataService.SuspendMyActivities(procInstID);
        }

        /// <summary>
        /// 恢复MyActivity
        /// </summary>
        /// <param name="procInstID"></param>
        public static void ResumeMyActivities(int procInstID)
        {
            K2DataService.ResumeMyActivities(procInstID);
        }



        /// <summary>
        /// 根据流程ID获得第一个节点的名称(实际为第二个,因为要排除Start节点)
        /// </summary>
        /// <param name="procID"></param>
        /// <returns></returns>
        public static string GetFirstActivityName(int procID)
        {
            return K2DataService.GetFirstActivityName(procID);
        }

        /// <summary>
        /// 根据流程实例ID获得流程第一个节点的名称(实际为第二个,因为要排除Start节点)
        /// </summary>
        /// <param name="procID"></param>
        /// <returns></returns>
        public static string GetFirstActivityNameByInstID(int procInstID)
        {
            return GetFirstActivityName(K2DataService.GetProcID(procInstID));
        }

        public static void UpdateMyActivityInfo(MyActivityTableEntity entity)
        {
            MyActivityManager.Update(entity);
        }

        public static void MoveMyActivityList(List<MyActivityTableEntity> myActivityList)
        {
            if (myActivityList == null) return;
            List<Guid> guidList = new List<Guid>();
            foreach (MyActivityTableEntity myActivity in myActivityList)
            {
                if (myActivity.MyActivityID.HasValue)
                {
                    guidList.Add(myActivity.MyActivityID.Value);
                }
            }
            K2DataService.MoveMyActivityListToHistroy(guidList);
        }

        public static void MoveMyActivityList(Guid actionRecordId)
        {
            K2DataService.MoveMyActivityListToHistroy(actionRecordId);
        }

        public static void CreateNewMyActivityList(List<MyActivityTableEntity> myActivityList)
        {
            if (myActivityList == null) return;
            foreach (MyActivityTableEntity myActivity in myActivityList)
            {
                MyActivityManager.Insert(myActivity);
            }
        }

        public static UserDelegationTableEntity GetUserDelegationInfo(string categoryName, int userId)
        {
            UserDelegationTableEntitySet es = UserDelegationManager.SelectByCondition(
                string.Format("CategoryName='{0}' and UserID={1} and Disabled=0 and (FromDate is null or year(FromDate)*10000+month(FromDate)*100+day(FromDate)<={2}) and (ToDate is null or year(ToDate)*10000+month(ToDate)*100+day(ToDate)>={2})", categoryName, userId, DateTime.Now.ToString("yyyyMMdd"))
                );
            if (es.Count > 0)
                return es[0];
            return null;
        }

        public static Flow_ProcessTableEntitySet GetProcessAll()
        {
            IWebCache webCache = GetWebCacheRealtime();
            string key = "Flow_Process";
            object value = webCache.Get(key);
            Flow_ProcessTableEntitySet tempSet;
            if (value == null)
            {
                Flow_ProcessTableEntitySet processSet = Flow_ProcessManager.SelectAll();
                webCache.Add(key, processSet);
                tempSet = processSet;
            }
            else
            {
                tempSet = (Flow_ProcessTableEntitySet)value;
            }
            return tempSet;
        }

        public static Flow_ProcessTableEntity GetProcess(string procName)
        {
            Flow_ProcessTableEntitySet set = GetProcessAll();
            if (set == null) return null;
            return (Flow_ProcessTableEntity)set.GetEntity(0, string.Format("ProcName='{0}'", procName));
        }

        public static Flow_ProcessConfigTableEntitySet GetProcessConfigAll()
        {
            IWebCache webCache = GetWebCacheRealtime();
            string key = "Flow_ProcessConfig";
            object value = webCache.Get(key);
            Flow_ProcessConfigTableEntitySet tempSet;
            if (value == null)
            {
                Flow_ProcessConfigTableEntitySet processConfigSet = Flow_ProcessConfigManager.SelectAll();
                webCache.Add(key, processConfigSet);
                tempSet = processConfigSet;
            }
            else
            {
                tempSet = value as Flow_ProcessConfigTableEntitySet;
            }
            return tempSet;
        }

        public static Flow_ProcessConfigTableEntity GetProcessConfig(string procName, string activityName)
        {
            Flow_ProcessConfigTableEntitySet set = GetProcessConfigAll();
            return (Flow_ProcessConfigTableEntity)set.GetEntity(0, string.Format("ProcName='{0}' and ActivityName='{1}'", procName, activityName));
        }

        public static DataTable GetActivityLine(int ProcID)
        {
            return K2DataService.GetActivityLine(ProcID);
        }

        public static DataTable GetProcessStamp(int procInstId)
        {
            return K2DataService.GetProcessStamp(procInstId);
        }

        public static DataTable GetProcessStampEZVisit(int procInstId)
        {
            return K2DataService.GetProcessStampEZVisit(procInstId);
        }

        public static DataTable GetProcessStampPostEZVisit(int procInstId)
        {
            return K2DataService.GetProcessStampPostEZVisit(procInstId);
        }

        public static EmployeeTableEntity GetUserInfoById(int employeeID)
        {
            return EmployeeManager.SelectByCondition(string.Format("EmployeeID='{0}'", employeeID))[0];

        }

        public static EmployeeTableEntitySet GetUserInfoByUSER_CD(string user_cd)
        {
            return EmployeeManager.SelectByCondition(string.Format("EmployeeNo='{0}' and IsActived=1", user_cd));
        }

        public static EmployeeTableEntitySet GetUserInfosByROLE_CD(string role_cd)
        {
            return K2DataService.GetUserInfosByROLE_CD(role_cd);
        }

        public static MyActivityTableEntity GetOneOfMyActivities(int procInstId, int ownerId, int[] statusArr)
        {
            return K2DataService.GetOneOfMyActivities(procInstId, ownerId, statusArr);
        }

        public static int GetProcID(int procInstId)
        {
            return K2DataService.GetProcID(procInstId);
        }

        public static ProcessInstanceStatus GetProcessInstanceStatus(int procInstId)
        {
            int status = K2DataService.GetProcessInstanceStatus(procInstId);
            return (ProcessInstanceStatus)status;
        }

        public static K2User GetK2UserById(int userId)
        {
            EmployeeTableEntity entity = EmployeeManager.SelectByCondition(string.Format("EmployeeID='{0}'", userId))[0];
            if (entity == null) return null;
            K2User user = new K2User();
            user.UserId = userId;
            user.UserEn = entity.NameEN;
            user.UserCn = entity.NameChinese;
            return user;
        }

        public static Flow_ProcessMailConfigTableEntity GetProcessMailConfig(string procName, string activityName, string actionType)
        {
            IWebCache webCache = GetWebCacheRealtime();
            string key = "Flow_ProcessMailConfig";
            object value = webCache.Get(key);
            Flow_ProcessMailConfigTableEntitySet tempSet;
            if (value == null)
            {
                Flow_ProcessMailConfigTableEntitySet processMailConfigSet = Flow_ProcessMailConfigManager.SelectAll();
                webCache.Add(key, processMailConfigSet);
                tempSet = processMailConfigSet;
            }
            else
            {
                tempSet = value as Flow_ProcessMailConfigTableEntitySet;
            }
            return (Flow_ProcessMailConfigTableEntity)tempSet.GetEntity(0, string.Format("ProcName='{0}' and ActivityName='{1}' and ActionType='{2}'", procName, activityName, actionType));
        }

        private static IWebCache GetWebCacheRealtime()
        {
            string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            return new SqlDependencyWebCache(connectionString);
        }
    }
}
